<template>
  <a-modal :open="open" width="930px" title="手术文书" centered :footer="false" @cancel="onCancel">
    <div class="flex">
      <div class="w-1/2">
        <BaseTable
          column-code="000264"
          :data-source="tableData"
          :custom-row="
            (record) => ({
              onClick: () => {
                handelrImage(record)
              }
            })
          "
          :row-class-name="(record) => (record.id === selectedRowKey ? 'selected-row' : '')"
          :loading="loading"
          :height="300"
          bordered
        >
          <template #bodyCell="{ column, index, record }">
            <template v-if="column.dataIndex == 'xh'">
              {{ index + 1 }}
            </template>
            <template v-if="column.dataIndex == 'wh'">
              <a-tag :color="record.wh === '未维护' ? 'red' : 'green'">{{ record.wh }}</a-tag>
            </template>
          </template>
        </BaseTable>
      </div>
      <div class="w-1/2 pr-2">
        <a-form :model="formBattalion" name="validate_other" :label-col="{ style: { width: '95px' } }">
          <a-form-item name="image" label="上传文书" class="w-full" :rules="[{ required: true, message: '' }]">
            <div class="clearfix">
              <a-upload v-model:file-list="fileList" list-type="picture-card" :custom-request="beforeUpload" @remove="onRemove" @preview="handlePreview">
                <div>
                  <PlusOutlined />
                  <div style="margin-top: 8px">上传照片</div>
                </div>
                <!-- <div v-if="fileList.length !== 3">

                </div> -->
              </a-upload>
              <a-modal :open="previewVisible" width="70%" :footer="null" @cancel="handleCancel">
                <div class="w-full h-full mt-6">
                  <img
                    alt="example"
                    style="width: 100%; height: 100%; transition: transform 0.5s"
                    :style="{ transform: `rotate(${rotateDegree}deg)` }"
                    :src="previewImage"
                  />
                </div>
              </a-modal>
            </div>
          </a-form-item>
        </a-form>
      </div>
    </div>
    <a-space class="flex justify-end p-4">
      <a-button @click="onCancel">取消</a-button>
      <a-button type="primary" :disabled="!fileList.length" @click="onSave">保存</a-button>
    </a-space>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import axios from 'axios'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const rotateDegree = ref(0)
const previewVisible = ref(false)
const previewImage = ref('')
const selectedRowKey = ref('')
const tableData = ref([])
const fileList = ref([])
const formState = ref({})
const formBattalion = ref({})
const { loading, getData } = useTable({
  url: '/oprOperation/opr/getOphthOprDocumentList',
  pagination: false,
  formatParams: () => {
    return {
      oprLsh: formState.value.lsh,
      pageNum: 1,
      pageSize: 999
    }
  },
  formatResult: (data) => {
    selectedRowKey.value = selectedRowKey.value || data[0].id
    tableData.value = data
    handelrImage(data.filter((item) => item.id === selectedRowKey.value)[0])
  }
})

// 上传
const beforeUpload = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg'
  if (!isJpgOrPng) {
    message.error('请上传jpg或者png格式!')
    fileList.value = fileList.value.filter((item) => {
      return !item.type
    })
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  fileList.value = fileList.value.filter((item) => {
    return item.url
  })
  const { data: res } = await axios.post('/api/v1/common/util/doUploadFile', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  if (res.code !== 0) return message.error(res.msg)
  fileList.value.push({
    uid: fileList.value.length + 1,
    name: res.data.fileName,
    fileName: res.data.fileName,
    url: res.data.picturePath,
    fileUrl: res.data.picturePath,
    documentId: selectedRowKey.value,
    oprLsh: formState.value.lsh,
    id: res.data.id || undefined
  })
}

// 预览图片
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
const handleCancel = () => {
  previewVisible.value = false
}
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj)
  }
  previewImage.value = file.url || file.preview
  previewVisible.value = true
}

const onRemove = async (file) => {
  const { code, msg } = await post('/oprOperation/opr/doDelOphthOprDocument', { id: file.id })
  if (code !== 0) return message.error(msg || '失败')
  message.success(msg)
  getData()
}

const onSave = async () => {
  const res = await post('/oprOperation/opr/doSaveOphthOprDocumentList', fileList.value)
  if (res.code !== 0) return message.error(res.msg || '失败')
  message.success('保存成功')
  getData()
}

const handelrImage = (list) => {
  selectedRowKey.value = list.id
  fileList.value = []
  list.oprDocumentList.forEach((item, index) => {
    fileList.value.push({
      uid: index + 1,
      name: item.fileName,
      url: item.fileUrl,
      documentId: selectedRowKey.value,
      oprLsh: formState.value.lsh,
      fileName: item.fileName,
      fileUrl: item.fileUrl,
      id: item.id
    })
  })
}

// const handlerRotate = () => {
//   rotateDegree.value += 90
// }

const onCancel = () => {
  emit('update:open', false)
  emit('success')
  selectedRowKey.value = ''
  formBattalion.value = {}
  fileList.value = []
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      formState.value = { ...props.rowData }
      getData()
    }
  }
)
</script>
<style lang="less" scoped></style>
